<template>
	<view class="pay-content">
		<view class="top">
			<view>确认订单</view>
			<image src="/static/pay-close.png" @click="closePayDialog" />
		</view>

		<view class="order">
			<view class="info-wrapper">
				<view class="game-image">
					<image :src="image" />
				</view>

				<view class="game-content">
					<view>{{ title }}</view>
					<!-- <view class="game-item">
						<text>单价</text>
						<text v-if="gameType === 'Z福利'">{{ price }}</text>
						<text v-else>¥{{ (price/100).toFixed(2) }}</text>
					</view> -->
					<view class="game-item">
						<!-- <text>数量</text> -->
						<!-- <view v-if="prices && prices.length" class="seats">
							<view v-for="count in counts" class="seat" :key="count" @click="() => changeSeat(count)"
								:class="localCount === count ? 'active': ''">
								<text>{{countLabels[count.toString()]}}位</text>
							</view>
						</view> -->
						<text>x{{ localCount }}</text>
					</view>
					<view class="game-item1" style="text-align: right;">
						<!-- <text>合计</text> -->
						<!-- <text>¥{{ (price * localCount / 100).toFixed(2) }}<text></text> -->
						<text>¥{{ (price / 100).toFixed(2) }}</text><text
							style="color: #FFDD86;font-size: 20rpx;">/抽</text>
					</view>
				</view>
			</view>
			<view class="wish" v-if="wishItems&&wishItems.length>0">
				<view class="wishitem" v-for="(e,i) in wishItems" :key="i">
					<button @click="selectwish(i)"
						:class="[e.id==wishItemselect?'wishbtn select':'wishbtn']">{{e.name}}</button>
				</view>
			</view>
			<view class="method">
				<view class="paymethod">
					<view class="alipay">
						<image class="aliicon" src="/static/owo/alipay.png"></image>
						<text class="txt">支付宝支付</text>
					</view>
					<view class="righticon">
						<!-- <image src="/static/owo/selectsoild.png" class="noselect"></image> -->
						<image src="/static/owo/seelcted.png" class="select"></image>
					</view>
				</view>
				<view class="paymethod">
					<view class="alipay">
						<image class="aliicon" src="/static/owo/coin.png"></image>
						<text class="txt">余额支付</text>
					</view>
					<view class="righticon" @click="toggleUseScore">
						<text class="score">余额：{{score}}</text>
						<image src="/static/owo/selectsoild.png" class="noselect" v-if="!useScore"></image>
						<image src="/static/owo/seelcted.png" class="select" v-else></image>
					</view>
				</view>
			</view>
			<!-- 选择优惠券 -->
			<view
				style="display: flex; flex-direction: column;border-bottom: solid 1rpx rgba(255, 255, 255, 0.20);padding-bottom: 24rpx;">
				<view v-if="gameType !== 'Z福利'" class="coupon-select items-center"
					style="background-color: #33333F;height: 88rpx;">
					<view class="items-center" style="margin-right: 17px;">
						<image src="/src/static/owo/cuponicon.png" style="width: 32rpx;height: 24rpx;"></image>
						<text>优惠券</text>
					</view>
					<!-- <text>剩余:{{ myCoupons.length }}张</text> -->
					<view class="coupon-selector items-center justify-end" @click="showCouponDialog">
						<text v-if="willUseCoupon" style="color: white">{{ willUseCoupon.name }}</text>
						<text v-else>{{ myCoupons.length > 0 ? '有可用优惠卷': '暂无可用'}}</text>
						<uni-icons type="right" color="#B7B7BB" size="14" style="height: 15px"></uni-icons>
					</view>
				</view>

				<!-- <view v-if="gameType !== 'Z福利'" class="coupon-select items-center">
					<view class="items-center" style="margin-right: 17px">
						<view class="list-icon"></view>
						<text>使用动车票抵扣</text>
					</view>
					<text>剩余:{{ score }}张</text>
					<view class="coupon-selector items-center justify-end">
						<view class="radio-rear" @click="toggleUseScore">
							<image class="pay-radio" src="/static/pay-radio.png" />
							<image v-if="useScore" class="pay-select" src="/static/pay-selected.png" />
						</view>
					</view>
				</view> -->
			</view>
		</view>
		<view class="agreement">
			<view class="radio-rear" @click="changeProtocolState">
				<image class="pay-radio" src="/static/owo/selectsoild.png" />
				<image v-if="protocolState" class="pay-select" src="/static/owo/seelcted.png" />
			</view>
			<view>
				我已阅读并同意
				<text class="protocol" @click="gotoRichText('购买协议')">《购买协议》</text>
				和
				<text class="protocol" @click="gotoRichText('隐私条款')">《隐私条款》</text>
			</view>

		</view>
		<view class="tips">
			<view>购买赏品后请到赏袋申请发货，平台将于7个工作日内发出，全平台满5件即享包邮，不满5件，邮费10元。</view>
			<!-- <view>购买赏品后请到赏袋申请发货，运费10元，商品满6件包邮(含大陆偏远地区)。</view> -->
			<!-- <view>用户申请发货后平台于15天内发货。</view> -->
			<!-- <view>抽赏存在概率性请合理消费，未成年人禁止消费。</view> -->
		</view>


		<view class="pay-btn" @click="payment">
			立即支付 {{ totalPrice }} {{ unit }}
		</view>

		<van-dialog use-slot :show="couponDialogVisible" :show-confirm-button="false" width="280">
			<my-coupon-dialog-content :coupons="myCoupons" v-on:close="couponDialogVisible = false"
				v-on:confirm="useCoupon" />
		</van-dialog>
		<van-dialog use-slot :show="payMethodDialogVisible" :show-confirm-button="false" width="312">
			<my-pay-method v-if="payMethodDialogVisible" v-on:close="payMethodDialogVisible = false"
				:price="paymentDetail.need" v-on:confirm="paymethod" />
		</van-dialog>
	</view>
</template>

<script lang="ts">
	export default {
		name: 'Pay'
	}
</script>

<script lang="ts" setup>
	import { ref, reactive, computed, watch, onMounted } from 'vue'
	import { getMyCoupons } from '@/api/coupons'
	import { recharge, checkWallet } from '@/api/pay'
	import { loadWallet, loadUserInfo } from '@/api/user'
	import { buyYiFanShang, buyInfinite, buyPk, buyZWeal, buyCouple } from "@/api/pay";
	import MyCouponDialogContent from '@/wxcomponents/my-coupon-dialog-content'
	import MyPayMethod from '@/wxcomponents/my-pay-method'

	let props = defineProps([
		'wishItems',
		'gameId',
		'gameType',
		'gameIndex',
		'image',
		'price',
		'prices',
		'title',
		'count',
		'position',
		'isFull'
	])

	let wishItemselect = ref(0);// 许愿卡id
	const emit = defineEmits(['close', 'success'])
	let value = ref(null)
	const localCount = ref(props.count)
	const prices = ref(props.prices || [])

	const totalPrice = ref(0)
	const buyGifts = ref([])
	const couponDialogVisible = ref(false)
	const payMethodDialogVisible = ref(false);
	const willUseCoupon = ref(null)
	let paymentDetail = ref({
		need: 0
	});
	const score = ref(0)
	const useScore = ref(true)
	const myCoupons = ref([])
	let protocolState = ref(false)
	let unit = ref('元')

	watch(() => props.count, (newV) => {
		localCount.value = newV
		updatePrice()
	})

	const countLabels = {
		1: '一',
		3: '三',
		5: '五',
		10: '十',
		12: '十二',
	}

	const counts = computed(() => props.prices.map(p => p.count))

	function updatePrice() {
		totalPrice.value = (props.price || 0) * (localCount.value || 0)
		if (willUseCoupon.value) {
			if (willUseCoupon.value.type === '满减') {
				totalPrice.value = totalPrice.value - willUseCoupon.value.discount
			}
			if (willUseCoupon.value.type === '折扣') {
				totalPrice.value = totalPrice.value * (willUseCoupon.value.rate / 100)
			}
		}
		if (props.gameType !== 'Z福利') {
			totalPrice.value = (totalPrice.value / 100).toFixed(2)
			unit.value = '元'
		}
		if (props.gameType == 'Z福利') {
			unit.value = 'Z元素'
		}
	}

	async function changeSeat(seat) {
		localCount.value = seat
		await Promise.all([
			reloadCoupons(),
			reloadWallet()
		])
		updatePrice()
	}

	function toggleUseScore() {
		useScore.value = !useScore.value
	}

	function gotoRichText(type : string) {
		wx.navigateTo({
			url: `/pages/subPackage/rich-text/index?type=` + type,
		})
	}

	async function payment() {
		if (!protocolState.value) {
			uni.showToast({
				title: '请先同意《购买协议》和《隐私条款》',
				icon: 'none'
			})
			return
		}

		if (!props.count) {
			uni.showToast({
				title: '库存不足',
				icon: 'none'
			})
			return
		}
		if (props.gameType == '对对碰') {
			if (!wishItemselect.value) {
				uni.showToast({
					title: '请选择许愿卡',
					icon: 'none'
				})
				return
			}
		}
		let checkParas = {
			game_type: props.gameType,
			game_id: props.gameId,
			count: localCount.value,
			is_full: props.isFull,
			use_score: useScore.value ? 1 : 0,
			coupon_id: willUseCoupon.value?.id
		}
		// 查看余额
	
		let checkRes = await checkWallet(checkParas)
		paymentDetail.value = checkRes.data
		payMethodDialogVisible.value = true;
		if (checkRes.data.enough === 1) {
			// 余额充足
			gamePayment()
		} else {
			if (props.gameType === 'Z福利') {
				uni.showToast({
					title: '余额不足',
					icon: 'none'
				})
				return
			}
			paymentDetail.value = checkRes.data
			payMethodDialogVisible.value = true;

			// // 使用支付小程序跳转
			// let pages = getCurrentPages(); // 获取当前页面栈
			// let currentPage = pages[pages.length - 1]; // 获取当前页面实例
			// let data = {
			// 	price: checkRes.data.need,
			// 	url: currentPage.$page.fullPath,
			// 	user_id:user_id.value
			// }
			// console.log(data)

			// // 余额不足
			// wx.navigateToMiniProgram({
			// 	appId: 'wxc0375ba1f1d91db6',
			// 	path: '/pages/index/index',//要打开B小程序的页面
			// 	extraData: data,//需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
			// 	envVersion: 'trial',//打开的对应小程序环境：开发develop、体验trial、生产release
			// 	success(res) {
			// 		console.log('打开成功', res)
			// 	}
			// })
			// 默认的支付
			// const { data } = await recharge({ price: checkRes.data.need })
			// const jspay = data.jspay

			// uni.requestPayment({
			// 	provider: 'wxpay',
			// 	"appid": 'wx900d129b8768ed6b',
			// 	"timeStamp": jspay.timestamp,
			// 	"nonceStr": jspay.nonceStr,
			// 	"package": jspay.package,
			// 	"signType": jspay.signType,
			// 	"paySign": jspay.paySign,
			// 	success: function (res) {
			// 		gamePayment()
			// 	},
			// 	fail: function (err) {
			// 		uni.showToast({
			// 			title: '取消支付',
			// 			icon: 'none'
			// 		})
			// 	}
			// })
		}
	}
	function wxpayment() {
		let pages = getCurrentPages(); // 获取当前页面栈
		let currentPage = pages[pages.length - 1]; // 获取当前页面实例
		let data = {
			price: paymentDetail.value.need,
			url: currentPage.$page.fullPath,
			user_id: user_id.value
		}
		console.log(data)
		// 余额不足
		wx.navigateToMiniProgram({
			appId: 'wxc0375ba1f1d91db6',
			path: '/pages/index/index',//要打开B小程序的页面
			extraData: data,//需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
			envVersion: 'trial',//打开的对应小程序环境：开发develop、体验trial、生产release
			success(res) {
				console.log('打开成功', res)
			}
		})
	}
	async function gamePayment() {
		let gifts = []
		if (props.gameType === '一番赏' || props.gameType === '欧皇赏') {
			const data = {
				type: props.gameType,
				index: props.gameIndex,
				game_id: props.gameId,
				count: localCount.value,
				coupon_id: willUseCoupon.value?.id,
				use_score: useScore.value ? 1 : 0,
			}

			const res = await buyYiFanShang(data)
			gifts = res.data.gifts || []
			buyGifts.value = gifts
		} else if (props.gameType === '动力赏') {
			// 购买动力赏
			const data = {
				game_id: props.gameId,
				count: localCount.value,
				coupon_id: willUseCoupon.value?.id
			}

			const res = await buyInfinite(data)
			gifts = res.data.gifts || []
			buyGifts.value = gifts
		} else if (props.gameType === 'Z福利') {
			// 购买扭蛋机
			const data = {
				id: props.gameId,
				count: localCount.value,
				coupon_id: willUseCoupon.value?.id
			}

			const res = await buyZWeal(data)
			gifts = res.data.gifts || []
			buyGifts.value = gifts
		} else if (props.gameType === '欧皇对决') {
			// 二人对战
			const data = {
				type: props.gameType,
				game_id: props.gameId,
				count: localCount.value,
				position: props.position,
				is_full: props.isFull,
				coupon_id: willUseCoupon.value?.id
			}

			const res = await buyPk(data)
			gifts = res.data.gifts || []
			buyGifts.value = gifts
		} else if (props.gameType === '对对碰') {
			// 对对碰

			const data = {
				wish: wishItemselect.value,
				game_id: props.gameId,
				coupon_id: willUseCoupon.value?.id
			}

			const res = await buyCouple(data)
			willUseCoupon.value = null // 重置当前支付窗口的优惠券选项
			await reloadCoupons()
			emit('close')
			emit('success')
			return
		}

		buyGifts.value = gifts
		willUseCoupon.value = null // 重置当前支付窗口的优惠券选项
		await reloadCoupons()
		emit('close')
		emit('success', gifts)
	}
	function selectwish(index : number) {
		wishItemselect.value = props.wishItems[index].id
	}
	function closePayDialog() {
		willUseCoupon.value = null // 重置当前支付窗口的优惠券选项
		emit('close')
	}

	function showCouponDialog() {
		couponDialogVisible.value = true;
	}
	function paymethod(number) {
		if (number == 1) {
			uni.showToast({
				title: "联系客服",
				icon: "none"
			})
		} else if (number == 2) {
			wxpayment()
		} else if (number == 3) {
			wxpayment()
		}
		setTimeout(() => {
			payMethodDialogVisible.value = false;
		}, 200)
	}
	async function useCoupon(coupon) {
		couponDialogVisible.value = false;
		willUseCoupon.value = coupon
	}

	async function reloadCoupons() {
		const totalPriceValue = (props.price || 0) * (localCount.value || 0)
		const params = {
			use_state: '未使用',
			price: totalPriceValue
		}
		const res = await getMyCoupons(params)
		const data = res.data || {}
		const items = (data.items || []).filter((i) => i.use_state === '未使用')

		for (let i = 0; i < items.length; i++) {
			let showPrice = (items[i]['price'] / 100).toFixed(2)
			if (items[i]['type'] === '折扣') {
				showPrice = (items[i]['rate'] / 10).toFixed(1) + '折'
			}
			items[i]['showPrice'] = showPrice
		}

		myCoupons.value = items
	}

	async function reloadWallet() {
		const res = await loadWallet()
		score.value = res.data.score
	}

	// 切换协议选中状态
	function changeProtocolState() {
		protocolState.value = !protocolState.value
		uni.setStorageSync('protocolState', protocolState.value)
	}
	function loadProtocolState() {
		const state = uni.getStorageSync('protocolState')
		console.log('protocolState', state)
		if (state) {
			protocolState.value = Boolean(state)
		} else {
			protocolState.value = false
		}
	}

	let user_id = ref("");
	onMounted(async () => {
		loadProtocolState()

		await Promise.all([
			reloadCoupons(),
			reloadWallet(),
		])
		updatePrice()
		const userRes = await loadUserInfo()
		let userInfo = userRes.data || {}
		user_id.value = userInfo.user_id || ''
	})
</script>

<style scoped lang="scss">
	.method {
		width: 100%;
		margin-bottom: 24rpx;

		.paymethod {
			display: flex;
			justify-content: space-between;
			flex-direction: row;
			align-items: center;
			height: 100rpx;
			border-bottom: solid 1rpx rgba(255, 255, 255, 0.20);

			.alipay {
				flex-direction: row;
				align-items: center;
				display: flex;

				.aliicon {
					width: 44rpx;
					height: 44rpx;
				}

				.txt {
					color: #ffffff;
					font-size: 28rpx;
					padding-left: 12rpx;
				}
			}

			.righticon {
				display: flex;
				flex-direction: row;
				align-items: center;
			}

			.noselect {
				width: 36rpx;
				height: 36rpx;
			}

			.select {
				width: 36rpx;
				height: 36rpx;
			}

			.score {
				color: rgba(255, 255, 255, 0.65);
				font-size: 24rpx;
				padding-right: 12rpx;
			}
		}
	}

	.wish {
		width: 100%;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		align-items: center;
		justify-content: flex-start;

		.wishitem {
			margin-right: 18rpx;
			margin-bottom: 18rpx;

			.wishbtn::after {
				padding: 0;
				margin: 0;
			}

			.wishbtn {
				height: 50rpx;
				line-height: 50rpx;
				box-sizing: border-box;
				border: solid 2rpx #ffffff;
				border-radius: 15rpx;
				padding: 0rpx 16rpx;
				color: #ffffff;
				background-color: transparent;
			}

			.select {
				border-color: #E174ED !important;
				color: #E174ED;
			}
		}
	}

	.items-center {
		display: flex;
		align-items: center;
	}

	.justify-end {
		display: flex;
		justify-content: flex-end;
	}

	.seats {
		display: flex;
		gap: 10px;

		.seat {
			border-radius: 6px;
			width: 40px;
			height: 25px;
			display: flex;
			justify-content: space-around;
			align-items: center;
			border: 1px solid white;
		}

		.seat.active {
			background: linear-gradient(90deg, #205DE9 0%, #8E6CF4 100%);
			border-color: transparent;
		}
	}

	.radio-rear {
		position: relative;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: row;

		.pay-radio {
			width: 28rpx;
			height: 28rpx;
		}

		.pay-select {
			width: 28rpx;
			height: 28rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-top: -14rpx;
			margin-left: -14rpx;
		}
	}

	.pay-content {
		height: auto;
		padding-bottom: 1em;
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		border-radius: 15rpx 15rpx, 0rpx, 0rpx;
		background: #42424E;
		color: #FFF;
		z-index: 110;

		.top {
			display: flex;
			justify-content: space-between;
			padding: 28rpx;
			height: 60rpx;
			align-items: center;
			flex-direction: row;
			border-bottom: solid 1rpx rgba(255, 255, 255, 0.20);

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.order {
			display: flex;
			margin: 15rpx;
			padding: 20rpx;
			border-radius: 8rpx;
			flex-direction: column;
			// gap: 39rpx;

			.info-wrapper {
				display: flex;
				justify-content: space-between;
				padding: 20rpx 0;
				border-bottom: solid 1rpx rgba(255, 255, 255, 0.20);
			}

			.game-image {
				margin-right: 30rpx;

				image {
					height: 160rpx;
					width: 160rpx;
					border-radius: 6rpx;
				}
			}

			.game-content {
				flex: 1;
				width: 100%;

				.game-item {
					color: rgba(255, 255, 255, 0.65);
					margin-top: 10rpx;
					font-size: 28rpx;
				}

				.game-item1 {
					color: #FFDD86;
					margin-top: 10rpx;
					font-size: 36rpx;
				}
			}
		}

		.tips {
			margin: 15rpx;
			padding: 15rpx;
			line-height: 30rpx;
			color: rgba(255, 255, 255, 0.65);
			font-size: 22rpx
		}

		.agreement {
			margin: 15rpx;
			padding: 15rpx;
			display: flex;
			font-size: 24rpx;
			align-items: center;

			.protocol {
				color: #FFDD86;
				font-size: 24rpx;
			}
		}

		.pay-btn {
			margin: 40rpx 15rpx 0;
			text-align: center;
			height: 80rpx;
			color: #18181C;
			font-weight: bold;
			font-style: oblique;
			background: linear-gradient(90deg, #FFF7C2 0%, #FFD163 100%);
			line-height: 80rpx;
			border-radius: 0rpx;
		}

		.coupon-select {
			position: relative;
			display: flex;
			align-items: center;
			font-size: 12px;
			// padding-bottom: 24rpx;

			.list-icon {
				width: 5px;
				height: 5px;
				border-radius: 50%;
				background-color: #D85AE7;
				margin-right: 6px;
			}

			.coupon-selector {
				color: #626061;
				flex: 1;
				justify-content: flex-end;
			}
		}
	}
</style>